package com.jiefutong.zyt;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.jiefutong.zyt.bean.SendSmsBean;
import com.jiefutong.zyt.view.SecurityCodeView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.zhy.autolayout.AutoLayoutActivity;

import java.util.Timer;
import java.util.TimerTask;

public class BackCodeActivity extends AutoLayoutActivity {
    private TextView telTV;
    private SecurityCodeView codeViewTV;
    private TextView sendTV;
    private Button nextBtn;
    private String userMobile;
    private TimerTask mTimerTask;//计时器
    private int mRemainingTime = 59;
    private Handler mHandler = new Handler();
    private ImageView backBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_back_code);
        userMobile=getIntent().getStringExtra("userMobile");
        initView();
        loadData();
    }

    private void loadData() {
        startTimer();
        HttpParams params = new HttpParams();
        params.put("mobile", userMobile);
        params.put("type",  "changepassword ");
        OkGo.<String>post("https://zyt.jiefutong.net/api/index/api/sendsms")
                .tag(this)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        final SendSmsBean bean = JSON.parseObject(response.body(), SendSmsBean.class);
                        if (bean != null && bean.status.equals("success")) {
                            Toast.makeText(getBaseContext(),"发送成功", Toast.LENGTH_SHORT).show();
                            nextBtn.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    next();
                                }
                            });
                        }else{
                            if (bean.message.equals("手机号码已注册")) {
                                Toast.makeText(getBaseContext(), bean.message, Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(BackCodeActivity.this,bean.message, Toast.LENGTH_SHORT).show();
                                cancelTask();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });

    }

    public  void next(){
        showProgress(true);
        HttpParams params = new HttpParams();
        params.put("mobile", userMobile);
        params.put("code",  codeViewTV.getEditContent());
        OkGo.<String>post("https://zyt.jiefutong.net/api/index/api/check/sendsms")
                .tag(this)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        final SendSmsBean bean = JSON.parseObject(response.body(), SendSmsBean.class);
                        if (bean != null && bean.status.equals("success")) {
                           // Toast.makeText(getBaseContext(),"发送成功", Toast.LENGTH_SHORT).show();
                            Intent intent=new Intent(BackCodeActivity.this,BackSetPasswordActivity.class);
                            intent.putExtra("userMobile",userMobile);
                            intent.putExtra("code",codeViewTV.getEditContent());
                            startActivity(intent);
                        }else{
                            Toast.makeText(getBaseContext(), bean.message, Toast.LENGTH_SHORT).show();
                        }
                        showProgress(false);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showProgress(false);
                    }
                });

    }

    private void cancelTask() {
        mTimerTask.cancel();
        sendTV.setText("重新获取");
    }

    private void initView() {
        backBtn=findViewById(R.id.back_btn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        telTV=findViewById(R.id.backCode_telTV);
        codeViewTV=findViewById(R.id.backCode_codeViewTV);
        sendTV=findViewById(R.id.backCode_sendTV);
        nextBtn=findViewById(R.id.backCode_nextBtn);
        telTV.setText("验证码已发送至手机："+userMobile);
    }

    private void startTimer() {
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                mRemainingTime--;
                if (mRemainingTime == 0) {
                    mTimerTask.cancel();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            sendTV.setText("重新获取");
                        }
                    });
                    mRemainingTime = 59;
                    return;
                }
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        setTimePrompt();
                    }
                });
            }
        };
        Timer timer = new Timer();
        timer.schedule(mTimerTask, 1000, 1000);
    }

    private void setTimePrompt() {
        String timeFormat = "%1$d秒后重新获取";
        sendTV.setText(String.format(timeFormat, mRemainingTime));
    }


    /**
     * Shows the progress UI and hides the login form.
     */
    private ProgressDialog progress;
    public void showProgress(final boolean show) {
        if (progress == null) {
            progress = new ProgressDialog(
                    BackCodeActivity.this);
            progress.setMessage("正在加载...");
            progress.setCanceledOnTouchOutside(false);
        }

        if (show) {
            progress.show();
        } else {
            progress.dismiss();
        }
    }
}
